package cn.yuanqiao.archive.jiashicang.aspect;

import cn.yuanqiao.archive.jiashicang.annotation.AroundAnnotation;
import cn.yuanqiao.common.service.RedisService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class AroundAspect {

    private static final Logger log = LoggerFactory.getLogger(AroundAspect.class);

    @Autowired
    private RedisService redisService;

    @Pointcut("@annotation(cn.yuanqiao.archive.jiashicang.annotation.AroundAnnotation)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
//        MethodSignature signature = (MethodSignature) point.getSignature();
//        // 获取方法
//        Method method = signature.getMethod();
//        JudgeIsManualAdd annotation = method.getAnnotation(JudgeIsManualAdd.class);
//        String type = annotation.type();
//        Object[] args = point.getArgs();
        MethodSignature signature = (MethodSignature) point.getSignature();
        Object[] args = point.getArgs();
        String dayOrMonth = null;
        if(args!=null && args.length==1){
            dayOrMonth = (String)args[0];
        }
        // 获取方法
        Method method = signature.getMethod();
        String name = method.getName();

        AroundAnnotation annotation = method.getAnnotation(AroundAnnotation.class);
        String type = annotation.type();
        if("utilizing".equalsIgnoreCase(type)){
            if(dayOrMonth!=null){
                name+=":"+dayOrMonth;
            }
        }

        Object cacheObject = redisService.getCacheObject("cockPit:" + name);
        if(cacheObject==null){
            log.info("cockPit:" + name+" 方法结果集缓存未命中");
            cacheObject = point.proceed();
            //redisService.setCacheObject("cockPit:" + name,cacheObject,30L, TimeUnit.MINUTES);
            redisService.setCacheObject("cockPit:" + name,cacheObject);
            if(cacheObject!=null){
                log.info("cockPit:" + name+" 获取方法结果集，并缓存：：："+cacheObject.toString());
            }
        }else{
            log.info("cockPit:" + name+" 方法结果集缓存命中");
            if(cacheObject!=null){
                log.info("cockPit:" + name+" 方法结果集：：："+cacheObject.toString());
            }
        }
        return cacheObject;
       /* JudgeIsManualAdd annotation = method.getAnnotation(JudgeIsManualAdd.class);
        String type = annotation.type();
        Object[] args = point.getArgs();
        JSONObject arg = (JSONObject) args[0];*/

    }
}
